package com.kedacom.demo.redis.jedis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;

/**
 * RedisConnectionBrokenDetect
 * @author luocanfeng
 * @date 2016年12月27日
 */
public class RedisConnectionBrokenDetect {

	private static final Logger logger = LoggerFactory.getLogger(RedisConnectionBrokenDetect.class);

	private static final String redis_ip = "172.16.80.113";
	private static final int redis_port = 6379;
	private static final String redis_password = null;

	/**
	 * 获取Redis连接
	 */
	private static Jedis getJedis() {
		try {
			JedisShardInfo jsi = new JedisShardInfo(redis_ip, redis_port);
			if (redis_password != null) {
				jsi.setPassword(redis_password);
			}
			return new Jedis(jsi);
		} catch (Exception e) {
			logger.error("初始化Jedis失败，{}", e.getMessage());
			e.printStackTrace();
			return null;
		}
	}

	public static void startDetect() {
		Jedis jedis = getJedis();
		int pingFailed = 0;
		boolean isNewJedis = false;
		while (true) {
			try {
				jedis.ping();
				logger.debug("PONG");
				Thread.sleep(1000);
				if (isNewJedis) { // 重新连接Redis后
					logger.info("重连Redis成功。");
					// TODO: 通知重新订阅
					logger.info("已通知重新订阅。");
					isNewJedis = false;
					pingFailed = 0; // 失败计数清零
				}
			} catch (Exception e) {
				logger.info("PING Jedis失败，{}", e.getMessage());
				pingFailed++;
				if (isNewJedis || pingFailed > 3) {
					Jedis newJedis = getJedis();
					if (newJedis != null) {
						try {
							jedis.close();
						} catch (Exception e1) {
							logger.error("关闭Jedis连接失败，{}", e1.getMessage());
						}
						jedis = newJedis;
						isNewJedis = true;
					}
				}
			}
		}
	}

	public static void main(String[] args) {
		startDetect();
	}

}
